/*
 */
package beans;

import db_connect.DB;
import java.sql.Connection;
import java.text.ParseException;
import java.util.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Milan Boricic <boricic@gmail.com>
 */
public class NeradniDan {

    private Integer ndid;
    private Sala sala;
    private Date datum;
    private Timestamp vremeEvidentiranja;
    private Korisnik korisnik;
    private String razlog;

    private Date datumDo;
    private String datumOdString;
    private String datumDoString;
    private List<SelectItem> sale;
    private Integer salaId;

    public NeradniDan() {
    }

    public Date getDatum() {
        return datum;
    }

    public void setDatum(Date datum) {
        this.datum = datum;
    }

    public Korisnik getKorisnik() {
        return korisnik;
    }

    public void setKorisnik(Korisnik korisnik) {
        this.korisnik = korisnik;
    }

    public Integer getNdid() {
        return ndid;
    }

    public void setNdid(Integer ndid) {
        this.ndid = ndid;
    }

    public String getRazlog() {
        return razlog;
    }

    public void setRazlog(String razlog) {
        this.razlog = razlog;
    }

    public Sala getSala() {
        return sala;
    }

    public void setSala(Sala sala) {
        this.sala = sala;
    }

    public Timestamp getVremeEvidentiranja() {
        return vremeEvidentiranja;
    }

    public void setVremeEvidentiranja(Timestamp vremeEvidentiranja) {
        this.vremeEvidentiranja = vremeEvidentiranja;
    }

    public Date getDatumDo() {
        return datumDo;
    }

    public void setDatumDo(Date datumDo) {
        this.datumDo = datumDo;
    }

    public String getDatumDoString() {
        return datumDoString;
    }

    public void setDatumDoString(String datumDoString) {
        this.datumDoString = datumDoString;
    }

    public String getDatumOdString() {
        return datumOdString;
    }

    public void setDatumOdString(String datumOdString) {
        this.datumOdString = datumOdString;
    }

    public Integer getSalaId() {
        return salaId;
    }

    public void setSalaId(Integer salaId) {
        this.salaId = salaId;
    }
    
    public List<SelectItem> getSale() {
        sale = new ArrayList<SelectItem>();
        List<Sala> saleSve = new Sala().getSaleSve();

        sale.add(new SelectItem(null, "Izaberite salu..."));
        sale.add(new SelectItem(-1, "-- Sve sale --"));
        for(Sala s:saleSve) {
            sale.add(new SelectItem(s.getSid(), s.getNaziv()));
        }
        return sale;
    }

    public void setSale(List<SelectItem> sale) {
        this.sale = sale;
    }
    
    public static NeradniDan getDatumNeradan(Sala sala, Date datum) {
        NeradniDan neradan = null;
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;
        java.sql.Date d = new java.sql.Date(datum.getTime());
        try {
            con = DB.getConnection();
            stmt = con.createStatement();
            String query = "select * from neradni_dani where sid=" + sala.getSid() +
                    " and datum='" + d + "';";
            rs = stmt.executeQuery(query);

            if(rs.next()) {
                neradan = new NeradniDan();
                neradan.setNdid(rs.getInt("ndid"));
                neradan.setSala(sala);
                neradan.setDatum(datum);
                neradan.setVremeEvidentiranja(rs.getTimestamp("vreme_evidentiranja"));

                Integer kid = rs.getInt("korisnik");
                neradan.setKorisnik(DB.getKorisnik(kid));

                neradan.setRazlog(rs.getString("razlog"));
            }
            
            stmt.close();
            con.close();
        } catch (SQLException sqle) {
            
            sqle.printStackTrace();
            if (con != null) {
                try {
                    con.close();
                } catch (Exception exc) {
                }
            }
        }
        return neradan;
    }

    public List<NeradniDan> getNeradniDanByUpit(String query) {
        ArrayList<NeradniDan> neradni = null;

        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            con = DB.getConnection();
            stmt = con.createStatement();
            rs = stmt.executeQuery(query);
            neradni = new ArrayList<NeradniDan>();
            while (rs.next()) {
                NeradniDan neradan = new NeradniDan();
                neradan.setNdid(rs.getInt("ndid"));
                Sala s = DB.getSala(rs.getInt("sid"));
                neradan.setSala(s);
                neradan.setDatum(rs.getDate("datum"));
                neradan.setVremeEvidentiranja(rs.getTimestamp("vreme_evidentiranja"));
                Korisnik kor = DB.getKorisnik(rs.getInt("korisnik"));
                neradan.setKorisnik(kor);
                neradan.setRazlog(rs.getString("razlog"));

                neradni.add(neradan);
            }

            stmt.close();
            con.close();
        } catch (SQLException sqle) {
            sqle.printStackTrace();
            if (con != null) {
                try {
                    con.close();
                } catch (Exception exc) {
                }
            }
        }

        return neradni;
    }

    public List getNeradniDaniNakonDanas() {
        java.sql.Date sada = new java.sql.Date(System.currentTimeMillis());
        String query = "select * from neradni_dani where datum >= '" + sada + "';";
        List neradni = getNeradniDanByUpit(query);
        return neradni;
    }

    public String ponisti() {
        Connection con = null;
        Statement stmt = null;
        
        FacesContext context = FacesContext.getCurrentInstance();

        try {
            con = DB.getConnection();
            stmt = con.createStatement();

            String query = "delete from neradni_dani where ndid = " + ndid + ";";
            int res = stmt.executeUpdate(query);

            if(res == 1) {
                context.addMessage(null, new FacesMessage("Neradni dan obrisan!"));
            }

            stmt.close();
            con.close();
        } catch (SQLException sqle) {
            sqle.printStackTrace();
            if (con != null) {
                try {
                    con.close();
                } catch (Exception exc) {
                }
            }
        }
        return Korisnik.ACTION_ADMIN;
    }

    public String save() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
        korisnik = (Korisnik) session.getAttribute("korisnik");
        SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy.");

        try {
            datum = formatter.parse(datumOdString);
            if(datumDoString == null || "".equals(datumDoString)) {
                datumDoString = datumOdString;
            }
            datumDo = formatter.parse(datumDoString);
        } catch (ParseException ex) {
            context.addMessage(null, new FacesMessage("Greška pri obradi datuma"));
            return Korisnik.ACTION_ADMIN;
        }

        Calendar datOd = new GregorianCalendar();
        datOd.setTime(datum);

        Calendar datDo = new GregorianCalendar();
        datDo.setTime(datumDo);

        List<Date> datumi = new ArrayList<Date>();
        
        while(datOd.before(datDo)) {
            datumi.add(new Date(datOd.getTimeInMillis()));
            datOd.add(Calendar.DAY_OF_MONTH, 1);
        }

        datumi.add(datumDo);

        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            con = DB.getConnection();
            stmt = con.createStatement();
            StringBuffer query = new StringBuffer("insert into neradni_dani(sid, datum, vreme_evidentiranja, korisnik, razlog) values ");
            Timestamp sada = new Timestamp(System.currentTimeMillis());
            Iterator iter = datumi.iterator();
            while(iter.hasNext()) {
                Date dat = (Date) iter.next();
                if(salaId == -1) {
                    List<Sala> tmpSale = new Sala().getSaleSve();
                    Iterator iterSale = tmpSale.iterator();
                    while(iterSale.hasNext()){
                        Sala s = (Sala) iterSale.next();
                        query.append("("+s.getSid()+", '"+new java.sql.Date(dat.getTime())+"', '"+sada+"', "+korisnik.getKid()+", '"+razlog+"')");
                        if(iterSale.hasNext() || iter.hasNext()) {
                            query.append(",");
                        }
                    }
                } else {
                    query.append("("+salaId+", '"+new java.sql.Date(dat.getTime())+"', '"+sada+"', "+korisnik.getKid()+", '"+razlog+"')");
                    if(iter.hasNext()) {
                        query.append(",");
                    }
                }
                

            }
            query.append(";");

            stmt.executeUpdate(query.toString());

            stmt.close();
            con.close();
        } catch (SQLException sqle) {
            sqle.printStackTrace();
            if (con != null) {
                try {
                    con.close();
                } catch (Exception exc) {
                }
            }
        }

        return Korisnik.ACTION_ADMIN;
    }
    
}
